/**
 * 重置密码控制器
 */
angular
.module('myApp')
.controller('resetController', function($scope, $timeout, userManager) {

  $scope.$watch('isSubmitted', function(newValue) {
    (true === newValue)
      ? $.showLoading('提交中...')
      : $.hideLoading();
  });

  $scope.$watch('captchaSecond', function(newValue) {
    var timer;
    if (angular.isDefined(newValue) && (newValue > 0)) {
      $scope.captchaButton = '发送验证码 ('+newValue+')';
      timer = $timeout(function() {
        $scope.captchaSecond --;
      }, 1000);
    } else {
      $timeout.cancel(timer);
      $scope.captchaButton = '发送验证码';
    }
  });

  var getFirstError = function(errors) {
    for(var key in errors) break;
    return errors[key];
  }

  $scope.sendCaptcha = function() {
    $.showLoading('发送中...');
    userManager.sendCaptcha($scope.mobile)
      .then(function(data) {
        $.toptip('验证码已发送成功！', 'success');
        $scope.captchaSecond = 60;
      }, function(data) {
        var errorMessage = angular.isDefined(data.errors)
          ? getFirstError(data.errors)
          : data.msg;
        $.toptip(errorMessage, 'warning');
      })
      .finally(function() {
        $.hideLoading();
      });
  }

  $scope.processSubmit = function() {

    $scope.isSubmitted  = true;
    $scope.errorMessage = false;

    userManager.resetPassword($scope.mobile, $scope.password, $scope.repassword, $scope.captcha)
      .then(function(data) {
        $scope.success = true;
      }, function(data) {
        $scope.errorMessage = angular.isDefined(data.errors)
          ? getFirstError(data.errors)
          : data.msg;
      })
      .finally(function() {
        $scope.isSubmitted = false;
      });
  }
});
